package servlets;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jmysql.Cmysql;
import net.sf.jasperreports.engine.JasperRunManager;

/**
 * Servlet implementation class ReporteRequisicion
 */
@WebServlet("/ReporteRequisicion")
public class ReporteRequisicion extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReporteRequisicion() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String iddescarga=request.getParameter("iddescargaX");
		String reporte="ReporteRequisicion";//vamos a imprimir
		
		Map <String,Object>parameters = new HashMap<String,Object>();
		parameters.put("p_iddescarga",(String)iddescarga);
		
		Connection conexion;
			try {
				String realpath=getServletContext().getRealPath("/Reportes/"+reporte+".jasper");
				File reportFile = new File(realpath);
							
				conexion = (Connection) new Cmysql().dataSource.getConnection();	
				byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath (),parameters,conexion);
				response.reset();
				response.setContentType("application/pdf");
				response.setHeader( "Content-Disposition", "attachment; filename=\"REPORTE DE REQUISICION.pdf\"" );
				
				conexion.close();
				
				ServletOutputStream ouputStream = response.getOutputStream();
				ouputStream.write(bytes, 0, bytes.length);
				ouputStream.flush();
				ouputStream.close();
				
			} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		
	}

}
